<template>
	<div class="fillcontain" style="padding: 25px 15px 15px;">
			<div style="display:flex;">
				<exam-project-library-list @queryTableData="queryTableData" ref="projectLibrary">
          <template slot="btn-slot">
            <el-button
            type="danger"
            size="mini"
            style="margin: 12px 20px 0;"
            plain
            icon="el-icon-circle-plus-outline"
            @click="addProject"
            >添加项目
          </el-button>
          </template>
        </exam-project-library-list>
				<div class="right_box">
          <div class="right-title">基本信息</div>

					<div style="background-color:#fff;">
						<el-form :model="ruleForm" :rules="projectRules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
							inline>
							<el-form-item label="项目编号" prop="projectNumber" style="margin-top: 25px;">
								<el-input v-model="ruleForm.projectNumber" disabled></el-input>
							</el-form-item>
							<el-form-item label="项目代码" prop="projectCode" style="margin-top: 25px;">
								<el-input v-model="ruleForm.projectCode" :disabled="currentRow.isLock" :maxlength="50" @input="inputChange($event,ruleForm,'projectCode')"></el-input>
							</el-form-item>
							<el-form-item label="项目名称" prop="projectName" style="margin-top: 25px;">
								<el-input v-model="ruleForm.projectName" :disabled="currentRow.isLock" :maxlength="20"></el-input>
							</el-form-item>
						</el-form>
					</div>
          <div class="right-title">子项目信息</div>

					<!-- 新增按钮 -->
					<div>
						<el-button type="danger" plain style="margin: 15px;" @click="sonAddClick" :disabled="currentRow.isLock">新增</el-button>
            <el-button type="danger" @click="sonSaveClick" :disabled="currentRow.isLock">保存</el-button>
					</div>

					<!-- 子项目列表 -->
					<div style="margin-left:20px ;">
						<el-table 
              :data="tableData.slice((page.pageIndex-1)*page.pageSize,page.pageIndex*page.pageSize)"
              style="width: 100%"
              height="calc(100vh - 480px)"
              ref="table"
              highlight-current-row>
              <el-table-column align="center" type="index" min-width="85" label="序号"></el-table-column>
							<el-table-column label="子项目名称" min-width="150">
								<template slot-scope="scope">
									<el-input v-model="scope.row.projectName" placeholder="请输入" maxlength="20" :disabled="currentRow.isLock"></el-input>
									<!-- <span v-else>{{ scope.row.projectName }}</span> -->
								</template>
							</el-table-column>
							<el-table-column label="项目编号" min-width="150">
								<template slot-scope="scope">
									<el-input v-model="scope.row.projectNumber" placeholder="系统自动生成" maxlength="50" @input="inputChange($event,scope.row,'projectNumber')" disabled></el-input>
									<!-- <span v-else>{{ scope.row.itemNum }}</span> -->
								</template>
							</el-table-column>
							<el-table-column label="项目代码" min-width="150">
								<template slot-scope="scope">
									<el-input v-model="scope.row.projectCode" placeholder="请输入" maxlength="50" @input="inputChange($event,scope.row,'projectCode')" :disabled="currentRow.isLock"></el-input>
									<!-- <span v-else>{{ scope.row.itemCode }}</span> -->
								</template>
							</el-table-column>
							<el-table-column label="操作" width="75" align="center">
								<template slot-scope="scope">
                  <el-button type="text" icon="el-icon-delete" @click="handleDel(scope.$index,scope.row)" :disabled="currentRow.isLock"></el-button>
								</template>
							</el-table-column>
						</el-table>
            <!-- 分页 -->
            <el-row>
              <el-col :span="24">
                <div class="pagination">
                  <!-- 分页 -->
                  <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="page.pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="page.pageSize" :total="tableData.length" layout="total, sizes, prev, pager, next, jumper">
                  </el-pagination>
                </div>
              </el-col>
            </el-row>
					</div>
				</div>
			</div>

      <el-dialog
        title="添加项目"
        :visible.sync="addProjectVisible"
        v-if="addProjectVisible"
        :show-close="false"
        :close-on-click-modal="false"
        width="980px"
        center
        >
        <el-form ref="projectForm" :model="projectForm" label-width="150px" :rules="projectRules" style="overflow: hidden;">
          <el-row>
            <el-col :span="12" class="common-box">
              <el-form-item label="项目编号：">
                <el-input v-model="projectForm.projectNumber" placeholder="系统自动生成" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" class="common-box">
              <el-form-item label="项目代码：" prop="projectCode">
                <el-input v-model="projectForm.projectCode" placeholder="请输入项目代码" :maxlength="50" @input="inputChange($event,projectForm,'projectCode')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="common-box">
              <el-form-item label="项目名称：" prop="projectName">
                <el-input v-model="projectForm.projectName" placeholder="请输入项目名称" :maxlength="20"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="common-box">
              <el-form-item label="备注：">
                <el-input type="textarea" :rows="3" v-model="projectForm.remark" placeholder="请输入备注" :maxlength="400"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="projectSave">保 存</el-button>
          <el-button @click="projectReset">取 消</el-button>
        </span>
      </el-dialog>
	</div>
</template>

<script>
import { getExamProjectInfoApi,insExamProjectLibraryApi,saveSonProjectInfoApi,delSonProjectInfoApi } from "@/api/medicalLibrary/medicalbank";
import constant from "@/utils/constant";

import examProjectLibraryList from '../../../../common/examProjectLibraryList.vue'

export default {
	components: {
    examProjectLibraryList,
  },
	data() {
    return {
      // 体检项目库数据
			data: [],
			defaultProps: {
					children: 'children',
					label: 'label'
			},
			// 基本信息
			ruleForm: {
				projectCode: '',
        projectName: '',
        projectNumber: ''
			},
			//    子项表格
			tableData: [],
      // 分页
      page: {
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
      },
      currentRow: {},

      // 添加项目弹窗
      addProjectVisible: false,
      projectForm: {
        projectNumber: '',
        projectName : '',
        projectCode: '',
        remark: '',
      },
      projectRules: {
        projectCode: [
          { required: true, message: '请输入项目代码', trigger: 'blur' }
        ],
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
      },
    }
  },
	methods: {
    // 点击添加项目按钮
    addProject(){
      this.addProjectVisible = true
    },
		queryTableData(id, title, isLock , currentRow) {
      this.$refs.ruleForm.resetFields()
      this.currentRow = currentRow
      this.page = {
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
      }
      this.ruleForm = {
        id: '',
        projectCode: '',
        projectName: '',
        projectNumber: ''
      }
      this.tableData = []
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      getExamProjectInfoApi({ id: id }).then( res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if(res.resultCode == constant.SUCCESS) {
          this.ruleForm = {
            id: res.data.id,
            projectCode: res.data.projectCode,
            projectName: res.data.projectName,
            projectNumber: res.data.projectNumber,
          }
          this.tableData = res.data.examinationList || []
        }
      })
      .catch((err) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
      })
    },
    // 页数
    sizeChangeHandle(val) {
      this.page.pageSize = val;
      this.page.pageIndex = 1;
    },
    // 当前页
    currentChangeHandle(val) {
      this.page.pageIndex = val;
    },
    // 点击子项目列表删除按钮
    handleDel(_index,row){
      this.$confirm(`是否删除此子项目信息?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        if(row.id){
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          delSonProjectInfoApi({id: row.id}).then((res) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
            if(res.resultCode == constant.SUCCESS) {
              let currentIndex = (this.page.pageIndex - 1) * (this.page.pageSize) + _index
              this.tableData.splice(currentIndex, 1);
              let pageTotal = (this.page.pageIndex - 1)  * this.page.pageSize
              if(this.page.pageIndex != 1 && pageTotal >= this.tableData.length) this.page.pageIndex = this.page.pageIndex - 1
              this.$message.closeAll()
              this.$message.success('子项目删除成功')
            }
          })
          .catch((err) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
          });
        }else {
          let currentIndex = (this.page.pageIndex - 1) * (this.page.pageSize) + _index
          this.tableData.splice(currentIndex, 1);
          let pageTotal = (this.page.pageIndex - 1)  * this.page.pageSize
          if(this.page.pageIndex != 1 && pageTotal >= this.tableData.length) this.page.pageIndex = this.page.pageIndex - 1
          this.$message.closeAll()
          this.$message.success('子项目删除成功')
        }
      })
      .catch(() => {})
    },
    // 点击子项目新增按钮
    sonAddClick(){
      this.tableData.push({
        projectCode: '',
        projectName: '',
        projectNumber: '',
        projectLevel: '2'
      })
    },
    // 点击子项目保存接口
    sonSaveClick(){
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          try {
            this.tableData.forEach(item=>{
              if(!item.projectName) {
                this.$message.closeAll()
                this.$message.warning('子项目名称不能为空')
                throw new Error('')
              }
              /* else if(!item.projectNumber) {
                this.$message.warning('子项目编码不能为空')
                throw new Error('')
              } */
              /* else if(!item.projectCode) {
                this.$message.warning('子项目代码不能为空')
                throw new Error('')
              } */
            })
          } catch (error) {
            return
          }
          /* let numbers = this.tableData.map(item=>item.projectNumber)
          let arr1 = [...new Set(numbers)]
          if(arr1.length<numbers.length) {
            this.$message.warning('子项目编码不能重复')
            return
          } */
          this.saveSonProjectInfo()
        }
      });
    },
    saveSonProjectInfo(){
      let params = {
        ...this.ruleForm,
        examinationList: this.tableData
      }
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      saveSonProjectInfoApi(params).then( res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if(res.resultCode == constant.SUCCESS) {
          this.$message.closeAll()
          this.$message.success('保存成功')
          let numbers = this.$refs.projectLibrary.treeData[0].children.map(item=>item.projectNumber)
          this.$refs.projectLibrary.currentId = null
          this.$refs.projectLibrary.filterText = ''
          this.$refs.projectLibrary.getProjectLibraryList(numbers.indexOf(this.ruleForm.projectNumber))
        }
      })
      .catch((err) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
      })
    },
    inputChange(el,row,field){
      // let val = ''
      // if(field=='projectNumber') val = el.replace(/[^a-zA-Z\d\-]/g,"")
      // else val = el.replace(/[^a-zA-Z\d]/g,"")
      let val = el.replace(/[^a-zA-Z\d\-\_]/g,"")
      this.$set(row,field,val)
    },
    // 弹窗按钮
    // 点击确认
    projectSave(){
      this.$refs.projectForm.validate((valid) => {
        if (valid) {
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          insExamProjectLibraryApi(this.projectForm).then( res => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
            if(res.resultCode == constant.SUCCESS) {
              this.$message.closeAll()
              this.$message.success('新增成功')
              this.projectReset()
              setTimeout(()=>{
                this.$refs.projectLibrary.currentId = null
                this.$refs.projectLibrary.filterText = ''
                this.$refs.projectLibrary.getProjectLibraryList()
              },200)
            }
          })
          .catch((err) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
          })
        }
      });
    },
    // 点击取消
    projectReset(){
      this.addProjectVisible = false
      this.projectForm = {
        projectNumber: '',
        projectName : '',
        projectCode: '',
        remark: '',
      }
    }
	},
}

</script>

<style lang="less" scoped>
.right-title{
  background: #f8f8f8;
  padding: 10px 25px;
  margin-left: 15px;
  position: relative;
}
.right-title::before{
  content: '';
  position: absolute;
  top: 11px;
  left: 15px;
  width: 3px;
  height: 18px;
  background: #f76767;
}
.top_box {
    height: 50px;
    line-height: 50px;
    border-bottom: 1px solid rgb(241, 238, 238);
    margin-bottom: 15px;
}

.top_box h1 {
    font-weight: 600;
    margin-left: 15px;
}

.left_box {
    width: 400px;
    border: 1px solid #e3dddd;
}

.right_box {
  width: calc(100% - 350px);
    /* border: 1px solid #e3dddd; */
}
/deep/ .filter-tree {
  max-height: calc(100vh - 340px);
  overflow: auto;
}
</style>